package com.jumi.microservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.ResultEnum;
import com.jumi.microservice.common.core.aspect.WebLog;
import com.jumi.microservice.common.utils.HttpRquestUtil;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.SourceClassifyConfig;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.controller.base.BaseController;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.service.GoodsService;
import com.jumi.microservice.service.SourceMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商城素材表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-27
 */
@RestController
@Api(tags = "商城素材表 相关接口")
@RequestMapping("/commodity/source/material")
public class SourceMaterialController extends BaseController {

    @Autowired
    private SourceMaterialService sourceMaterialService;

    @Autowired
    private SourceClassifyConfig sourceClassifyConfig;

    @Autowired
    private GoodsService goodsService;


    @ApiOperation(value = "新增数据", notes = "新增一条商城素材表数据")
    @PostMapping("/add")
    @WebLog(description = "新增商城素材信息")
    public ResponseResult add(@Validated @RequestBody SourceMaterialVO sourceMaterial, HttpServletRequest request) {
        SourceMaterialDTO dto = vo2Dto(sourceMaterial);
        dto.setCreater(HttpRquestUtil.getUserName(request));
        dto.setModifier(HttpRquestUtil.getUserName(request));
        sourceMaterialService.insert(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "删除数据", notes = "删除指定ID商城素材表数据")
    @ApiImplicitParam(name = "ids", value = "ids")
    @DeleteMapping("/delete")
    @WebLog(description = "删除商城素材信息")
    public ResponseResult delete(@RequestParam String ids,  HttpServletRequest request) {
        sourceMaterialService.deleteByIds(ids, HttpRquestUtil.getUserName(request));
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID商城素材表数据")
    @PutMapping("/update")
    @WebLog(description = "更新商城素材信息")
    public ResponseResult update(@Validated @RequestBody SourceMaterialVO sourceMaterial, HttpServletRequest request) {
        SourceMaterialDTO dto = vo2Dto(sourceMaterial);
        dto.setCreater(HttpRquestUtil.getUserName(request));
        dto.setModifier(HttpRquestUtil.getUserName(request));
        sourceMaterialService.updateSm(dto);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "启用/禁用", notes = "商城素材启用/禁用")
    @PutMapping("/enableStatus")
    @WebLog(description = "商城素材启用/禁用")
    public ResponseResult enableStatus(@RequestParam Long id, @RequestParam Integer status, HttpServletRequest request) {
        sourceMaterialService.enableStatus(id, status, HttpRquestUtil.getUserName(request));
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "查询数据", notes = "获取指定ID商城素材表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<SourceMaterialVO> detail(@RequestParam Long id) {
        SourceMaterialDTO sourceMaterial = sourceMaterialService.selectById(id);
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(sourceMaterial==null);
        GoodsDTO goods = goodsService.getGoodsById(sourceMaterial.getSpuGoodsId());
        return ResultGenerator.genSuccessResult(dto2Vo(sourceMaterial, goods, sourceClassifyConfig.getClassify()));
    }


    @ApiOperation(value = "查询分页", notes = "获取商城素材表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse<List<SourceMaterialVO>> list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            SourceMaterialVO sourceMaterial) {
        LambdaQueryWrapper<SourceMaterialDO> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(sourceMaterial.getSpuGoodsName()), SourceMaterialDO::getSpuGoodsName,sourceMaterial.getSpuGoodsName());
        wrapper.ge(StringUtils.isNotEmpty(sourceMaterial.getStartTime()), SourceMaterialDO::getCreateTime,sourceMaterial.getStartTime());
        wrapper.le(StringUtils.isNotEmpty(sourceMaterial.getEndTime()), SourceMaterialDO::getCreateTime,sourceMaterial.getEndTime());
        //素材分类
        wrapper.eq(sourceMaterial.getSourceClassfy()!=null,SourceMaterialDO::getSourceClassfy,sourceMaterial.getSourceClassfy());
        wrapper.eq(sourceMaterial.getStatus()!=null, SourceMaterialDO::getStatus,sourceMaterial.getStatus());
        wrapper.eq(sourceMaterial.getModuleType()!=null, SourceMaterialDO::getModuleType,sourceMaterial.getModuleType());
        wrapper.eq(SourceMaterialDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.orderByDesc(SourceMaterialDO::getId, SourceMaterialDO::getUpdateTime);
        IPage<SourceMaterialDO> pageInfo = sourceMaterialService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()),pageInfo.getTotal());
    }

    @ApiOperation(value = "C端素材列表下拉", notes = "C端素材列表下拉")
    @GetMapping("/sourceListByName")
    public ResponseResult<List<SourceDropVO>> sourceListByName(@RequestBody SourceDropVO vo) {
        LambdaQueryWrapper<SourceMaterialDO> wrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotEmpty(vo.getSpuGoodsName())) {
            wrapper.and(i -> {
                i.like(SourceMaterialDO::getSpuGoodsName, vo.getSpuGoodsName())
                        .or()
                        .like(SourceMaterialDO::getMaterialDescription, vo.getSpuGoodsName());
            });
        }
        //商品分类id
        wrapper.eq(vo.getCategoryId()!=null&&vo.getCategoryId()!=0, SourceMaterialDO::getCategoryId,vo.getCategoryId());
        wrapper.eq(SourceMaterialDO::getStatus, StatusEnum.STATUS_YES.getCode());
        wrapper.eq(SourceMaterialDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.orderByDesc(SourceMaterialDO::getId, SourceMaterialDO::getUpdateTime);
        List<SourceMaterialDO> list = sourceMaterialService.list(wrapper);
        return ResultGenerator.genSuccessResult(
                list.stream().map(s->{
                    SourceDropVO svo = new SourceDropVO();
                    svo.setId(s.getId());
                    svo.setSpuGoodsName(s.getSpuGoodsName());
                    svo.setMaterialDescription(vo.getMaterialDescription());
                    return svo;
                }).collect(Collectors.toList()));
    }

    @ApiOperation(value = "添加素材-分类下拉", notes = "添加素材-分类下拉")
    @GetMapping("/sourceClassifies")
    public ResponseResult sourceClassifies() {
        return ResultGenerator.genSuccessResult(sourceClassifyConfig);
    }

    /**
     * vo->dto
     * @param vo
     * @return
     */
    private SourceMaterialDTO vo2Dto(SourceMaterialVO vo){
        SourceMaterialDTO dto = null;
        try {
            dto = vo.clone(SourceMaterialDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }

    /**
     * dto->vo
     * @param dto
     * @return
     */
    private SourceMaterialVO dto2Vo(SourceMaterialDTO dto, GoodsDTO goodsDTO, List<SourceClassifyVO> classify){
        SourceMaterialVO vo = null;
        try {
            vo = dto.clone(SourceMaterialVO.class);
            if(goodsDTO!=null){
                vo.setGoodsImage(goodsDTO.getGoodsImage());
                vo.setGoodsPrice(goodsDTO.getGoodsPrice());
            }
            packSourceClassfy(vo);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return vo;
    }

    /**
     * 列表对象转化
     * @param pos
     * @return
     */
    private List<SourceMaterialVO> pos2Vos( List<SourceMaterialDO> pos){
        return pos.stream().map(p->{
            SourceMaterialVO vo = null;
            try{
                vo = p.clone(SourceMaterialVO.class);
                packSourceClassfy(vo);
            }catch (Exception e){
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 封装素材分类名称
     * @param vo 返回素材信息
     */
    private void packSourceClassfy(SourceMaterialVO vo){
        SourceClassifyVO sourceClassify = sourceClassifyConfig.getClassify().stream().filter(cla->cla.getClassifyType().equals(vo.getSourceClassfy())).findAny().orElse(null);
        if(sourceClassify!=null){
            vo.setSourceClassfyName(sourceClassify.getClassifyName());
        }
    }

}
